<?php

//
// +------------------------------------------------------------------------+
// | PHP Version 5.4                                                        |
// +------------------------------------------------------------------------+
// | Copyright (c) All rights reserved.                                     |
// +------------------------------------------------------------------------+
// | 世纪车来车往(北京）网络科技有限公司 版权所有！                              |
// | TEL:010-63732365  HOTLINE:400-6688-365  EMAIL:clcw@clcw.com.cn         |
// | $Revision: 1.0 $                                                       |
// +------------------------------------------------------------------------+
// | Author: anguolei@clcw.com.cn                                           |
// +------------------------------------------------------------------------+
//
/**
 * 回车
 */

namespace AuctionBack\Controller;

use AuctionBack\Logic\ConsultLogic;
use AuctionBack\Logic\OwnerConfirmLogic;
use AuctionBack\Logic\RecheckLogic;
use AuctionCore\Account\Back\Employee;
use AuctionCore\AuctionOrder\AuOrder;
use AuctionCore\CarResource\Car;
use AuctionCore\Common\AjaxPage;
use AuctionCore\AuctionOrder\CarReturn;
use AuctionCore\AuctionOrder\Recheck;
use AuctionCore\CarOwner\Owner;
use AuctionCore\Finance\Collection;
use AuctionCore\Issue\OwnerIssue;
use AuctionCore\Other\Store;
use AuctionCore\ChangeOrder\ChangeOrder;
use AuctionCore\System\SystemConf;
use AuctionBack\Logic\ProceduresRequirementLogic;

class ReCheckController extends BaseController
{
    public function __construct()
    {
        parent::__construct();
        $this->emp_id = $this->user_info['emp_id'];
    }

    //待复检
    public function index()
    {
        $this->display();
    }

    //复检列表
    public function recheck_list()
    {
        $page = I("get.p/d", 1);
        $limit = 10;
        $t = I('get.t', 0);
        $location_area = I('get.location_area', 0);
        if ($location_area == 0) {
            $location_area = $this->user_info['bc_code'];
        } else {
            $location_area = [$location_area];
        }
        $order_no = I("get.order_num", '');
        $checker = I("get.checker", '');
        $seller_name = I("get.seller_name", '');
        $seller_phone = I("get.seller_phone", '');
        $params = [
            'status' => $t,
            'location_area' => $location_area,
            'order_no' => $order_no,
            'checker' => $checker,
            'seller_name' => $seller_name,
            'seller_phone' => $seller_phone
        ];
        $rc = new Recheck();
        $result = $rc->get_list($page, $limit, $params);
        $total = $result['total'] > 0 ? $result['total'] : 0;
        $list = $result['list'] > 0 ? $result['list'] : [];
        $Page = new AjaxPage($total, $limit, "get_page");
        $Page->setConfig('theme', " %totalRow% %header% %nowPage%/%totalPage% 页 %first% %upPage% %prePage% %linkPage% %downPage% %nextPage% %end% %jumpform%");
        $page_show = $Page->show();

        $this->assign('p', $page);
        $this->assign('status', $t);
        $this->assign('location_area', $location_area);
        $this->assign('order_no', $order_no);
        $this->assign('checker', $checker);
        $this->assign('page', $page_show);
        $this->assign('list', $list);
        $this->display();
    }

    //复检信息  return_check_status 3:待复检，4:复检跟踪，5:车况相符,6:不符,7:协商成功
    public function recheck_info()
    {
        $order_id = I("get.oid/d", 0);
        if ($order_id < 1) {
            $this->helpJsRedirect("参数不正确");
        }
        $o = new AuOrder($order_id);
        $detail = $o->get_return_detail();
        $s = new Store();
        if ($detail['car_source'] == 1) {
            //回车信息
            $return_detail = CarReturn::get_detail_by_order_id($order_id);
            $procedures = explode('、', $return_detail['procedure']);
            $c = new Car($detail['car_id']);
            $store = $s->detail(['store_id' => $return_detail['delive_store']]);
            $return_detail['delive_store_str'] = $store['store_name'];
            $desc = $c->detail('car_perform');
            $return_detail['desc'] = $desc['other_info'];
            $this->assign('return_detail', $return_detail);
        } else {
            $procedures = SystemConf::getConfValueByName("RETURN_PROCEDURES", 1);
        }
        //获取成交确认信息
        if ($detail['is_consult'] == 0) {
            $dealtData = OwnerConfirmLogic::getDealtByOrderId($order_id);
            $detail['owner_confirm_service'] = $dealtData['service_id'];
            $detail['owner_confirm_remark'] = $dealtData['remark'];
            $detail['owner_confirm_time'] = $dealtData['createtime'];
        } else {
            $dealtData = ConsultLogic::getDealtByOrderId($order_id);
            if (empty($dealtData)) {
                $dealtData = OwnerConfirmLogic::getConsultByOrderId($order_id);
                $detail['owner_confirm_service'] = $dealtData['service_id'];
                $detail['owner_confirm_remark'] = $dealtData['consult_remark'];
                $detail['owner_confirm_time'] = $dealtData['updatetime'];
            } else {
                $detail['owner_confirm_service'] = $dealtData['emp_id'];
                $detail['owner_confirm_remark'] = $dealtData['consult_remark'];
                $detail['owner_confirm_time'] = $dealtData['createtime'];
            }
        }
        
        $employee = new Employee($detail['owner_confirm_service']);
        $empData = $employee->user_info();
        $detail['owner_confirm_name'] = $empData['real_name'];
        $detail['owner_confirm_mobile'] = $empData['mobile'];

        //获取复检信息
        $recheckInfo = RecheckLogic::getDataByOrderId($order_id);
        if ($recheckInfo['status'] > 1) {
            $detail['procedure_checker'] = Employee::user_info_id($recheckInfo['procedure_checker'])['real_name'];
            $detail['condition_checker'] = Employee::user_info_id($recheckInfo['condition_checker'])['real_name'];
            $detail['recheck_time'] = $recheckInfo['recheck_time'];
            $detail['recheck_remark'] = $recheckInfo['remark'];
            $detail['recheck_procedures'] = $recheckInfo['procedures'];
        } else {
            $group_id = C("RECHECK_STAFF");
            //获取门店复检员
            if ($detail['car_source'] == 1) {
                $recheck_staff_list = $s->get_store_emp_by_store_group($return_detail['delive_store'], $group_id);
            } else {
                if ($detail['sign_service_method'] == 3) {
                    $recheck_staff_list = $s->get_store_emp_by_store_group($detail['sign_reserve_store'], $group_id);
                } else {
                    $recheck_staff_list = Employee::emp_branch_group($this->user_info['branch_id'], $group_id);
                }
            }
            $this->assign("recheck_staff_list", $recheck_staff_list);
        }

	    //获取手续上传要求
	    $prLogic = new ProceduresRequirementLogic($detail['sid']);
	    $beforeTransfer = $prLogic->getListByTransferStatus(1);
	    $afterTransfer = $prLogic->getListByTransferStatus(2);
	    $this->assign('beforeTransfer', $beforeTransfer);
	    $this->assign('afterTransfer', $afterTransfer);

        $this->assign("recheck_info", $recheckInfo);
        $logs = Recheck::get_trace_log($order_id);
        $this->assign("procedures", $procedures);
        $this->assign("logs", $logs);
        $this->assign('detail', $detail);
        $this->display();
    }

    //核实无误
    public function saveRecheck()
    {
        $id = I('post.id/d', 0);
        if ($id < 1) {
            $this->helpJsonResult(400, "参数错误");
        }
        $status = I("post.status/d");
        if ($status < 1) {
            $this->helpJsonResult(400, "复检状态不正确");
        }
        //验证复检前置状态
        $rl = new RecheckLogic($id);
        $recheckInfo = $rl->detail();
        if ($recheckInfo['status'] > 1) {
            $this->helpJsonResult(500, "复检状态异常,请联系管理员");
        }
        //验证拍单信息
        $order_id = $recheckInfo['order_id'];
        $o = new AuOrder($order_id);
        $order = $o->detail();
        if (empty($order)) {
            $this->helpJsonResult(400, "未找到拍单信息");
        }
        if ($order['is_lock'] == 1) {
            $this->helpJsonResult(500, "拍单已锁定");
        }
        if ($order['status'] != 7 && $order['status'] != 8) { //检查拍单状态
            $this->helpJsonResult(500, "拍单异常,请联系管理员");
        }
        $recheck_time = I('post.recheck_time', '');
        $condition_checker = I('post.recheck_man/d', 0);
        if ($condition_checker < 1) {
            $this->helpJsonResult(400, "请选择复检人员");
        }
        if (empty($recheck_time)) {
            $this->helpJsonResult(400, '请选择复检时间');
        }
        $is_car_condition_conform = I('post.vehicle_condition/d', 0);
        if ($is_car_condition_conform < 1) {
            $this->helpJsonResult(400, '请选择车况');
        }
        $condition_desc = I("post.condition_desc", '');
        if ($is_car_condition_conform == 2 && empty($condition_desc)) {
            $this->helpJsonResult(400, '请输入车况描述');
        }
        $procedures = I('post.procedures', '');
        $data = [
            'rl_id' => $id,
            'status' => $status,
            'order_id' => $order_id,
            'car_id' => $recheckInfo['car_id'],
            'emp_id' => $this->emp_id,
            'condition_checker' => $condition_checker,
            'procedures' => $procedures,
            'is_car_condition_conform' => $is_car_condition_conform,
            'condition_desc' => $condition_desc,
            'recheck_time' => $recheck_time,
        ];
        $actionName = $is_car_condition_conform == 1 ? "复检核实无误" : "复检车况不符";
        $remark = "复检完成";
        if ($status == 1) { //继续跟踪的
            //下次跟踪时间
            $data['next_trace_time'] = I('post.next_trace_time','');
            if(empty($data['next_trace_time'])){
                $this->helpJsonResult(400,"请选择下次跟踪时间");
            }
            //跟踪原因
            $data['trace_reason'] = I("post.trace_reason",'');
            if(empty($data['trace_reason'])){
                $this->helpJsonResult(400,"请输入跟踪原因");
            }
            $actionName = "复检继续跟踪";
            $remark = $data['trace_reason'];
        }
        $res = $rl->saveRecheck($data);
        if (!$res) {
            $this->helpJsonResult(500, "操作失败");
        }

        $this->log_record($order_id, $order['car_id'], $actionName, $remark);
        $this->helpJsonResult(200, 'success');
    }

    //记录日志信息
    private function log_record($order_id, $car_id, $action, $remark)
    {
        //记录员工操作日志
        $log = [
            'emp_id' => $this->emp_id,
            'order_id' => $order_id,
            'car_id' => $car_id,
            'owner_id' => 0,
            'action' => $action
        ];
        \AuctionCore\System\SystemLog::add($log);

        /**
         * 记录车辆跟踪日志
         */
        $employee = M("employee")->find($this->emp_id);
        $car_action_data = array(
            'action_name' => $action,
            'emp_id' => $this->emp_id
        );
        \AuctionCore\CarResource\Car::add_car_trace_log($car_id, $car_action_data);

        /**
         * 记录拍品跟踪日志
         */
        $order_action_data = array(
            'action_name' => $action,
            'emp_id' => $this->emp_id
        );
        \AuctionCore\AuctionOrder\AuOrder::add_order_trace_log($order_id, $order_action_data);
        $create_time = date('Y-m-d H:i:s', time());
        //记录复检跟踪日志
        Recheck::save_trace_log($order_id, $this->emp_id, $employee['real_name'], $action, $remark, $create_time);
    }

    //违约
    public function violate()
    {
        $order_id = I("post.order_id/d", 0);
        if ($order_id < 1) {
            $this->helpJsonResult(400, "参数错误");
        }
        $o = new AuOrder($order_id);
        $orderInfo = $o->detail();
        if ($orderInfo['is_lock'] == 1) {
            $this->helpJsonResult(400, "拍单已锁定");
        }
        $poInfo = $o->getPurchaseByOrderId();
        $c = new Car($orderInfo['car_id']);
        $carInfo = $c->detail();
        $car_plate_number = C('PLATE_PREFIX')[$carInfo['plate_prefix']] . $carInfo['plate_suffix'];
        $data = [];
        $data['order_id'] = $order_id;
        $data['order_no'] = $orderInfo['order_no'];
        $data['po_id'] = $poInfo['id'];
        $data['po_no'] = $poInfo['purchase_order_nu'];
        $data['car_plate_number'] = $car_plate_number;
        $data['order_status'] = $orderInfo['status'];
        $data['source'] = 2;
        $data['originator'] = $this->emp_id;
        $res = ChangeOrder::CreateChangeOrder($data);
        if (!$res) {
            $this->helpJsonResult(400, '处理失败');
        } else {
            $this->log_record($order_id, $orderInfo['car_id'], "复检发起违约");
            $this->helpJsonResult(200, '处理成功');
        }
    }
}
